package PlanTree;

import java.util.ArrayList;

import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.Tree;

import exec.util;

public class SemanticAnalyze {
	private ArrayList<String> columns = new ArrayList<String>();
	private String table = null;
	private AlgebraTree planTree = null;
	private AlgebraTree currentNode = null;
	
	public void senmanticAnalyze(CommonTree parseTree)
	{
		if(parseTree ==null)
		{
			System.out.println("The Sql Input parse tree is error.");
			return;
		}
		readTableAndColumns(parseTree);
	}
	private void readTableAndColumns(CommonTree tree)
	{
//		System.out.println(g.toString());
		if(tree==null)
		{
			return;
		}

		System.out.print("\t");
		for(int i=0; i < tree.getChildCount(); i++)
		{
			if(tree.token.toString().equals("Predicate") || tree.token.toString().equals("Column"))
				columns.add(((CommonTree)tree.getChild(0)).token.toString());//add column
			if(tree.token.toString().equals("Table"))
				table = ((CommonTree)tree.getChild(0)).token.toString();//add table
			
			Tree temp = tree.getChild(i);
			readTableAndColumns((CommonTree) temp);
		}
	}
	public boolean checkColumns(String tableName, ArrayList<String> columnList)
	{
		for(String c: columnList)
		{
			if(!checkColumn(tableName, c))
			{
				System.out.println("Analyze Error: column " + c);
				return false;
			}
		}
		return true;
	}
	
	private boolean checkColumn(String tableName, String column)
	{
		//neeed to be done
		return false;
	}
	
	private boolean checkTable(String table)
	{
		if(util.isTableExists(table))
			return false;
		return true;
	}
	
	public AlgebraTree generatePlanTree(CommonTree parseTree)
	{
		generateAlgebraTree(parseTree);
		AlgebraTree node = currentNode.child = new AlgebraTree();
		node.operator="scan";
		node.table = table;
		return planTree;
	}
	
	public void generateAlgebraTree(CommonTree parseTree)
	{
		//first build the map node as root
		if(parseTree.token.toString().equals("SelectStmt"))
		{
			planTree = new AlgebraTree();
			planTree.operator = "select";
			currentNode = planTree;
			
		}
		if(parseTree.token.toString().equals("Predicate"))
		{
			AlgebraTree node = currentNode.child = new AlgebraTree();
			node.operator="condition";
//			node.condition
			node.condition.put(((CommonTree)parseTree.getChild(0)).token.toString(), ((CommonTree)parseTree.getChild(2).getChild(0)).token.toString());
			currentNode = node;
			return;
		}
		
		for(int i=0; i < parseTree.getChildCount(); i++)
		{
			Tree temp = parseTree.getChild(i);
			readTableAndColumns((CommonTree) temp);
		}
	}
	
	public void printPlanTree(AlgebraTree tree)
	{
		if(tree ==null)
			return;
		System.out.println(tree.operator);
		printPlanTree(tree.child);
	}
}
